import axios from 'axios'
import store from '@/store'
import storage from 'store'
import router from '../router'
import notification from 'ant-design-vue/es/notification'
import Modal from 'ant-design-vue/es/modal'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import qs from 'qs'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 600000 // 请求超时时间
})
// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error,'error')
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    // const token = storage.get(ACCESS_TOKEN)
    const token = sessionStorage.getItem(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          router.push({ name: 'login' })
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
    if(error.response.status === 555){
      notification.error({
        message: 'Forbidden',
        description: error.response.message
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // 除却登录接口，其他接口需要判断用户权限，
  if(store.getters.roles.length !== 0 && config.headers.name){
    // 
    if(!store.getters.roles.includes(config.headers.name)){
      throw {response: {status: 555,message: '暂无当前接口请求权限！'}};
    }
  }

  // const token = storage.get(ACCESS_TOKEN)
  const token = sessionStorage.getItem(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  console.log(config,'config')
  if(!config.headers.file){
    // console.log('是否会走这里')
    if (token && !config.headers.noToken) {
      // config.headers['access-token'] = token
  
      var tokenObj = new Object()
      tokenObj[ACCESS_TOKEN] = token
      // console.log(config.params,'config')
      if(config.params){
        config.params = Object.assign(config.params,tokenObj)
      }else{
        config.data = Object.assign(config.data,tokenObj)
      }
      
      
    }
    config.data = qs.stringify(config.data)
  }else{
    config.data.append(ACCESS_TOKEN,token)
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  console.log(response,'response')
  if(response.data.errCode == 'ERROR_TOKEN'){
    // token 过期的操作
    Modal.confirm({
      title: '温馨提示',
      content: '当前登录已过期，请重新登录',
      onOk() {
        // console.log(store,'store')   
        sessionStorage.clear()
        store.dispatch('Logout').then(() => {
          router.push({ name: 'login' })
          setTimeout(() => {
            window.location.reload()
          },500)
        })
      },
    })
  }else{
    return response.data
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
